package tool;

import java.util.Date;
import java.util.Objects;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import bean.Contact;

public class ObjectConverter {
    public static final String PATTERN = "yyyy-MM-dd";
    private static SimpleDateFormat format = new SimpleDateFormat(PATTERN);

    public static Date parseTextToDate(String text) throws ParseException {
        try {
            if (Objects.nonNull(text)) {
                return text.length() > 1 ? (Date) format.parse(text) : null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String formatDateToText(Date date) {
        try {
            if (Objects.nonNull(date)) {
                return format.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int parseStringToInteger(String text) {
        try {
            if (Objects.nonNull(text)) {
                return text.length() > 0 ? Integer.parseInt(text) : 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static int parseStringToSexInteger(String text) {
        try {
            if (Objects.nonNull(text)) {
                return text.length() > 0 ? Contact.sex(Integer.parseInt(text)) : Contact.UNKNOWN_SEX;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Contact.UNKNOWN_SEX;
    }

    public static int castObjectToInteger(Object value) {
        try {
            if (Objects.nonNull(value)) {
                return (int) value;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
